<template>
  <div class="login-container">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left">

      <div class="title-container">
        <h3 class="title">园区管理系统--园区端</h3>
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="username"
          v-model="loginForm.username"
          placeholder="Username"
          name="username"
          type="text"
          tabindex="1"
          auto-complete="on"
        />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          :key="passwordType"
          ref="password"
          v-model="loginForm.password"
          :type="passwordType"
          placeholder="Password"
          name="password"
          tabindex="2"
          auto-complete="on"
          @keyup.enter.native="handleLogin"
        />
        <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>
      <p @click="alertVal = true" style="color: #fff;margin-bottom: 40px;">没有账号，立即注册？</p>
      <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleLogin">Login</el-button>

    </el-form>
    <vxe-modal v-model="alertVal" title="填写注册信息" width="30%" height="70%">
      <template #default>
        <el-form :model="formData" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm">
          <el-form-item label="园区名称:" prop="name" required>
                <el-input v-model="formData.name"></el-input>
            </el-form-item>
            <el-form-item label="园区地址:" prop="address" required>
                <el-input v-model="formData.address"></el-input>
            </el-form-item>
            <el-form-item label="园区面积:" prop="area" required>
                <el-input v-model.number="formData.area"></el-input>
            </el-form-item>
            <el-form-item label="园区房间数量:" prop="houseNum" required>
                <el-input v-model.number="formData.houseNum"></el-input>
            </el-form-item>
            <el-form-item label="园区简介:" prop="introduce" required>
                <el-input v-model="formData.introduce" type="textarea"></el-input>
            </el-form-item>
            <el-form-item label="邮箱:" prop="email" required>
                <el-input v-model="formData.email" type="email"></el-input>
            </el-form-item>
            <el-form-item label="园区banner图:">
                <el-upload
                  action="http://192.168.1.193:9307/api-user/open/uploadFile"
                  list-type="picture-card"
                  ref="myUpload1"
                  :headers="myHeaders"
                  :on-remove="handleRemove"
                  :before-upload="beforeAvatarUpload"
                  :on-success="handleAvatarSuccess">
                  <i class="el-icon-plus"></i>
                  <div slot="tip" class="el-upload__tip">上传的图片只能是 JPG 或者 PNG 格式!</div>
                </el-upload>
                <el-dialog>
                  <img width="100%" :src="formData.bannerImage" alt="">
                </el-dialog>
            </el-form-item>
            <el-form-item label="园区小图:" >
                <el-upload
                  action="http://192.168.1.193:9307/api-user/open/uploadFile"
                  list-type="picture-card"
                  ref="myUpload2"
                  :limit="1"
                  :on-remove="handleRemove"
                  :before-upload="beforeAvatarUpload"
                  :on-success="handleAvatarSuccess2">
                  <i class="el-icon-plus"></i>
                  <div slot="tip" class="el-upload__tip">上传的图片只能是 JPG 或者 PNG 格式! 且只能上传1张小图。</div>
                </el-upload>
                <el-dialog>
                  <img width="100%" :src="formData.minImageUrl" alt="">
                </el-dialog>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
                <el-button @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
            
        </el-form>
      </template>
      </vxe-modal>
  </div>
</template>

<script>
// import { validUsername } from '@/utils/validate'
import {register} from '@/api/register'
export default {
  name: 'Login',
  data() {
  var checkEmail = (rule, value, callback) => {
    const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
    if (!value) {
      return callback(new Error('邮箱不能为空'))
    }
    setTimeout(() => {
      if (mailReg.test(value)) {
        callback()
      } else {
        callback(new Error('请输入正确的邮箱格式'))
      }
    }, 100)
  }
    return {
      loginForm: {
        username: 'admin',
        password: '123456'
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', message: '请输入账号' }],
        password: [{ required: true, trigger: 'blur', message: '请输入密码' }]
      },
      loading: false,
      passwordType: 'password',
      redirect: undefined,
      //弹窗
      alertVal: false,
      formData: {
        name: '',
        address: '',
        area: null,
        houseNum: null,
        introduce: '',
        email: '',
        bannerImage: [],
        minImage: [],
        status: 0
      },
      rules: {
        name: [
          { required: true, trigger: 'blur', message: '请输入园区名称' },
        ],
        address: [
          { required: true, trigger: 'blur', message: '请输入园区地址' }
        ],
        area: [
          { required: true, trigger: 'blur', message: '请输入园区总面积' },
          { type: 'number', message: '园区面积必须为数字值'}
        ],
        houseNum: [
          { required: true, trigger: 'blur', message: '请输入园区房屋数量' },
          { type: 'number', message: '园区房屋数量必须为数字值'}
        ],
        introduce: [
          { required: true, trigger: 'blur', message: '请输入园区简介' }
        ],
        email: [
          {  required: true, validator: checkEmail, trigger: 'blur' }
        ]
      },
      myHeaders:{},
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  mounted(){
      this.myHeaders = { 'client_id':  'jeecp ', 'client_secret': 'webApp'}
  },
  methods: {

    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      // this.$router.push({ path: this.redirect || '/' })
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('user/login', this.loginForm).then(() => {
            this.$router.push({ path: this.redirect || '/' })
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 弹窗
    // 上传
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJPG) {
        this.$message.error('上传的图片只能是 JPG 或者 PNG 格式!');
      }
      return isJPG;
    },
    handleAvatarSuccess(res, file) {
      console.log("res", res)
      this.formData.bannerImage.push(res.data)
    },
    handleAvatarSuccess2(res, file) {
      console.log("res", res)
      this.formData.minImage.push(res.data)
    },
    // 提交表单
    submitForm(formName){
      this.$refs[formName].validate((valid) => {
          if (valid) {
            console.log('成功')
            if(this.formData.minImage.length != 0 && this.formData.bannerImage.length !=0 ){
              this.loading = true
              // 数组转为字符串--字符串转为数组  str.split(',')
              this.formData.bannerImage = this.formData.bannerImage.toString()
              this.formData.minImage = this.formData.minImage.toString()
              console.log("this.formData", this.formData)
              // formData
              register(this.formData).then(res => {
                console.log('提交注册信息成功！', res)
                 this.$refs[formName].resetFields();
                  setTimeout(() => {
                    this.alertVal = false
                    this.loading = false
                    this.$message({message: '提交成功！等待审核！',type: 'success'});
                    // 清除上传图片
                    this.$refs['myUpload1'].clearFiles();
                    this.$refs['myUpload2'].clearFiles();
                    this.formData = {
                      name: '',
                      address: '',
                      area: '',
                      houseNum: '',
                      introduce: '',
                      bannerImage: null,
                      minImage: null,
                      status: 0
                    }
                  }, 300)
              }).catch(err => {
                console.log(err)
              })
            }else{
              this.$message.error('请上传园区相关图片！');
            }
          } else {
            console.log('失败')
          }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg:#283443;
$light_gray:#fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-form .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-form {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;
    

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg:#2d3a4b;
$dark_gray:#889aa4;
$light_gray:#eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;
  position: relative;

  .login-form {
    position: relative;
    width: 450px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
    position: absolute;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    padding: 0 !important;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}

::v-deep.vxe-form .vxe-form--item{
  width: 100% !important;
}
::v-deep.vxe-form .vxe-form--item:last-of-type{
  margin-top: 50px;
}
</style>
